package org.csu.bbs.controller;

import org.csu.bbs.result.Result;
import org.csu.bbs.result.User;
import org.csu.bbs.service.impl.UserServiceImpl;
import org.csu.bbs.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class ImgController {

    @Autowired
    UserServiceImpl userService;

    //上传帖子图片
    @CrossOrigin
    @PostMapping("api/imgs")
    @ResponseBody
    public String imgUpload(MultipartFile file) throws Exception {
        String folder = System.getProperty("user.dir")+"\\imgs";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8443/api/file/"+ f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    //上传用户头像
    @CrossOrigin
    @PostMapping("api/avatar")
    @ResponseBody
    public Result avatarUpload(@RequestBody User user) {
        return userService.changeAvatar(user);
    }
}
